//项目结项
<template>
  <div class="flex-1 flex-ver">
    <div class="mb8">
      <search @clearSearch='clearSearch' :status='true'>
        <el-form label-width='93px' inline autocomplete="off" :model="pageparm" class="search_box">
          <el-form-item label="项目名称">
            <el-input size="medium" clearable v-model="pageparm.name" placeholder="请输入项目名称搜索" />
          </el-form-item>
          <el-form-item label="负责人姓名">
            <inputSearch ref="search_e" placeholder="请输入负责人姓名搜索" @onChange='searchChane($event,"leader_id")' />
          </el-form-item>
          <el-form-item label="负责人类型">
            <el-select size="medium" v-model="pageparm.leader_type" clearable
              @change='searchChane($event,"leader_type")' placeholder="请选择负责人类型搜索">
              <el-option v-for="item in firstType" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="科室" v-if="adminShow">
            <inputSearch ref="search_d" type='departments' @onChange='searchChane($event,"departments_id")' />
          </el-form-item>
          <el-form-item label="项目级别">
            <el-select size="medium" v-model="pageparm.project_level" clearable
              @change='searchChane($event,"project_level")' placeholder="请选择项目级别">
              <el-option v-for="item in projectLevel" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="开始日期">
            <el-date-picker v-model="pageparm.start_time" type="daterange" range-separator="至" start-placeholder="时间范围"
              end-placeholder="时间范围" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
              @change="searchChane($event,'start_time')">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="终止日期">
            <el-date-picker v-model="pageparm.end_time" type="daterange" range-separator="至" start-placeholder="时间范围"
              end-placeholder="时间范围" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
              @change="searchChane($event,'end_time')">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="审核状态">
            <el-select size="medium" clearable v-model="pageparm.review_status" placeholder="请选择审核状态搜索"
              @change='searchChane($event,"review_status")'>
              <el-option v-for="item in reviewStatus" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <p slot="footer" class="flex-1 tx-r c-6">
          <svg class="icon f-20" aria-hidden="true" slot="image">
            <use xlink:href="#icon-tishi"></use>
          </svg>温馨提示：中检审核通过，并且不处于变更状态中的项目才能提交结项申请。
        </p>
      </search>
    </div>
    <el-table :data="tableData" class="flex-1" height="100%" size="medium" border highlight-current-row
      v-loading="tableLoading" stripe @sort-change="tableSortChange" @row-click='viewDetails'>
      <el-table-column align="center" v-for="(item,i) in headerList" :key="item.prop" :prop="item.prop"
        :label="item.label + (item.unit || '')" :width="item.width" :fixed="i === 0 ? true: false" show-overflow-tooltip
        :sortable="item.noSort?false:'custom'">
        <template slot-scope="scope">
          <template v-if="item.prop === 'departments_id'">
            {{ scope.row.department?scope.row.department.name:'' }}
          </template>
          <template v-else-if="item.prop === 'leader_id'">
            {{ scope.row.leader_info?scope.row.leader_info.name:''}}
          </template>
          <template v-else-if="item.prop === 'complete_id'">
            {{objToStr(scope.row.complete_name)}}
          </template>
          <template v-else-if="item.prop === 'review_status'">
            <span v-if="scope.row.review.review_comment"
              class="c-red">{{scope.row.status}}：{{scope.row.review.review_comment}}</span>
            <span v-else>{{scope.row.status}}</span>
          </template>
          <template v-else-if="item.prop === 'leader_type'">
            {{ echo(scope.row.leader_type,firstType) }}
          </template>
          <template v-else-if="item.prop === 'project_level'">
            {{ echo(scope.row.project_level,projectLevel) }}
          </template>
          <template v-else>
            {{ scope.row[item.prop] }}
          </template>
        </template>
      </el-table-column>
      <el-table-column fixed="right" align="center" label="操作" width="100">
        <div class="" slot-scope="scope">
          <el-tooltip effect="dark" content="提交结项材料" placement="bottom-end">
            <el-button v-if="scope.row.final" type="success" @click.stop="submitMaterials(scope.row)" size="small"
              icon="el-icon-s-promotion" circle></el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="查看结项审核结果" placement="bottom-end" v-if="scope.row.finalReview">
            <el-button type="primary" @click.stop="viewMiddleReview(scope.row.finalReview)" size="small"
              icon="el-icon-warning-outline" circle></el-button>
          </el-tooltip>
        </div>
      </el-table-column>
    </el-table>

    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
    <el-dialog :visible.sync="editFormVisible" width="680px" @close='dialogClose'
      :close-on-click-modal='false' :close-on-press-escape='false'>
      <h2 slot="title" class="tx-c">文件上传</h2>
      <el-form autocomplete="off" label-width="100px" class="form">
        <el-form-item v-for="(v,i) in upfilesObj" :key="'label' + v" :label="v">
          <div style="width: 500px">
            <p>
              <el-upload multiple action="/" :on-change="(file, fileList) => {onChangeFile(file, fileList, i)}"
                :on-remove="(file, fileList) => {onRemoveFile(file, fileList, i)}" :auto-upload="false"
                :file-list='fileObj[i]'>
                <el-button size="medium" type="primary">选择文件</el-button>
              </el-upload>
            </p>
            <div>
              <p v-for="(v) in uploadedList[i]" :key="'ed_' + v.id" class="p_cell flex-space-between">
                <span class="overhide_ shou" @click="uploadFiles(v.file_path,v.file_name)">
                  <i class="el-icon-document"></i> {{v.file_name}}
                </span>
                <i @click="delFiles(v.id,i)" class="el-icon-close mr4 shou"></i>
              </p>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="flex-justify-bcenter">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit" :loading='btnLoading'>确 定</el-button>
      </div>
    </el-dialog>
    <!-- 审核 -->
    <examine ref="examine" :item='examine_item' />
    <!-- 详情 -->
    <detail-info :info='details' ref="detail" />
  </div>
</template>

<script>
  import {
    Apiprojects,
    ApiprojectsChange,
    ApiprojectsAccept,
    ApiupLoadFiles
  } from '@/api'
  import {
    reviewStatus,
    firstType,
    projectLevel
  } from "@/assets/js"
  import {debounce,adminShow,objToStr} from "@/utils/index";
  import {headerList} from '../js/portrait'
  import detailInfo from '../components/details.vue'

  export default {
    name: 'project_personalPortrait_closing',
    components: {
      detailInfo,
    },
    data() {
      return {
        objToStr,
        adminShow: adminShow(),
        reviewStatus,
        firstType,
        projectLevel,
        tableData: [],
        editFormVisible: false,

        pageparm: {
          page: 1,
          perPage: 20,
          total: null,
          sort_str: null,
          sort_order: 'desc',
        },
        tableLoading: false,

        btnLoading: false,

        headerList,
        fileList: [],
        id: null,

        examine_item: {},

        details: {
          review: {}
        },
        editForm: {},

        upfilesObj: {
          7: '结题报告',
          8: '结题证明',
          // 9: '验收报告'
        },
        fileObj: {
          7: [],
          8: [],
          // 9: [],
        },
        uploadedList: {
          7: [],
          8: [],
          // 9: [],
        },
        del: [],
      }
    },
    mounted() {
      this.getList()
    },
    methods: {
      uploadFiles: debounce(function (url, name) {
        ApiupLoadFiles(url).then(res => {
          let a = document.createElement("a")
          a.href = URL.createObjectURL(res)
          a.download = name
          a.click()
          URL.revokeObjectURL(a.href)
        })
      }, 500, true),
      viewDetails(val) {
        this.details = val
        this.$refs.detail.showInfo = true
      },
      viewMiddleReview(val) {
        this.examine_item.review_status = val.review_status
        this.examine_item.review_comment = val.review_comment
        this.examine_item.view = true
        this.$refs.examine.examineShow = true
      },
      delFiles(id, i) {
        this.del.push(id)
        this.uploadedList[i] = this.uploadedList[i].filter(item => item.id !== id)
      },
      submitMaterials(val) {
        this.id = val.id
        for (const key in this.uploadedList) {
          this.uploadedList[key] = JSON.parse(JSON.stringify(val.files[key] || []))
        }
        this.editFormVisible = true
      },
      onChangeFile(file, fileList, i) {
        this.fileObj[i].push(file)
      },
      onRemoveFile(file, fileList, i) {
        this.fileObj[i] = fileList
      },
      submit: debounce(function () {
        const fileObj = this.fileObj
        let count = 0
        for (const key in fileObj) {
          count += (fileObj[key].length + this.uploadedList[key].length)
        }
        if (count === 0) {
          this.$message.error('至少上传一个文件')
          return
        }
        this.btnLoading = true
        const formData = new FormData()
        formData.append('reviewer_type', 4)
        for (const key in fileObj) {
          if (fileObj[key].length > 0) {
            fileObj[key].forEach(ele => {
              formData.append(`${key}[]`, ele.raw)
            });
          }
        }
        if (this.del.length > 0) {
          this.del.forEach(item => {
            formData.append(`del[]`, item)
          })
        } else {
          formData.append(`del[]`, [])
        }
        ApiprojectsChange(formData, this.id, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }).then(res => {
          this.$message.success('材料提交成功')
          this.btnLoading = false
          this.editFormVisible = false
          this.getList()
        }).catch(() => {
          this.btnLoading = false
          this.$message.error('材料提交失败')
        })
      }, 500, true),
      dialogClose() {
        for (const key in this.fileObj) {
          this.fileObj[key] = []
          this.uploadedList[key] = []
        }
        this.del = []
      },
      echo(i, arr) {
        let label
        for (const item of arr) {
          if (item.value === i) {
            label = item.label
            break;
          }
        }
        return label
      },
      tableSortChange(column) {
        if (column.order === "descending") {
          this.pageparm.sort_str = column.prop;
          this.pageparm.sort_order = "desc";
        } else if (column.order === "ascending") {
          this.pageparm.sort_str = column.prop;
          this.pageparm.sort_order = "asc";
        } else {
          this.pageparm.sort_str = null;
          this.pageparm.sort_order = null;
        }
        this.getList()
      },
      //搜索
      clearSearch() {
        this.$refs.search_e.clear()
        if (this.adminShow) this.$refs.search_d.clear()
      },
      searchChane(i, val) {
        this.pageparm[val] = i
        this.pageparm.page = 1
        this.getList()
      },
      //分页
      callFather(pageparm) {
        this.pageparm.page = pageparm.page
        this.pageparm.perPage = pageparm.perPage
        this.getList()
      },
      getList() {
        this.pageparm.type = 'final'
        this.tableLoading = true
        Apiprojects(this.pageparm).then(({
          data,
          page
        }) => {
          this.tableData = data || []
          this.pageparm.total = page.total
          this.tableLoading = false
        }).catch(() => {
          this.tableLoading = false
        })
      },
    },

  }
</script>
<style lang="less" scoped>
  .p_cell {
    padding-left: 4px;
    line-height: 1.8;

    span {
      margin-right: 40px;
    }
  }
</style>